import axios from 'axios'
import { Toast } from 'vant'
import { getToken, delToken } from './storage'
import router from '@/router/index'

const request = axios.create({
  baseURL: 'http://liufusong.top:8080/'
})

request.interceptors.request.use((config) => {
  config.headers.Authorization = `Bearer ${getToken()}`
  return config
}, (error) => {
  return Promise.reject(error)
})

request.interceptors.response.use((response) => {
  Toast(response.data.description)
  return response.data
}, (error) => {
  if (error.response) {
    if (error.response.status === 401) {
      delToken()
      Toast('请重新登录')
      router.push('/login')
    } else {
      // 如果有错误响应，就提示用户错误信息
      Toast(error.response.data.message)
    }
  }
  return Promise.reject(error)
})
export default request